<template>
  <follow-card-list 
    :followVOList="followVOList" 
    @update-follow-status="updateFollowStatus"
  />
  <van-empty v-if="(!followVOList || followVOList.length < 1) && (type === '0' || type === '2')" description="没有粉丝"/>
  <van-empty v-if="(!followVOList || followVOList.length < 1) && (type === '1' || type === '3')" description="没有关注"/>
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";
import FollowCardList from "../../components/FollowCardList.vue";
import myAxios from "../../plugins/myAxios";
import {useRoute} from "vue-router";
import {showToast} from "vant";
import {FollowVOType} from "../../models/followVO";

const route = useRoute();

const followVOList = ref<FollowVOType[]>([]);

const type = ref(route.query.type);
const userId = ref(route.query.userId ?? 0);

// 处理关注状态更新
const updateFollowStatus = (userId: number, isFollowed: boolean) => {
  const userIndex = followVOList.value.findIndex(user => user.id === userId);
  if (userIndex !== -1) {
    // 创建新数组并更新特定元素
    const updatedList = [...followVOList.value];
    updatedList[userIndex] = {
      ...updatedList[userIndex],
      isFollowed: isFollowed
    };
    followVOList.value = updatedList;
  }
};

onMounted(async () => {
  console.log('当前查询类型:', type.value);
  console.log('当前查询用户ID:', userId.value);
  
  try {
    const requestParams = {
      pageNum: 1,
      pageSize: 20,
      type: type.value,
      userId: userId.value,
    };
    
    console.log('请求参数:', requestParams);
    
    const res : any = await myAxios.post('/follow/list', requestParams);
    
    console.log('响应结果:', res);
    
    if (res?.code === 0) {
      // 确保数据结构与前端组件期望的一致
      if (res.data && Array.isArray(res.data)) {
        // 处理返回的数据，确保字段名称一致
        followVOList.value = res.data.map(item => ({
          id: item.id,
          username: item.username,
          avatarUrl: item.avatarUrl,
          isFollowed: !!item.isFollowed  // 确保转换为布尔值
        }));
        console.log('处理后的粉丝/关注列表数据:', followVOList.value);
      } else {
        followVOList.value = [];
        console.log('返回的数据不是数组或为空');
      }
      
      if (!followVOList.value || followVOList.value.length === 0) {
        console.log('返回的粉丝/关注列表为空');
      }
    } else {
      console.error('查询失败, 错误码:', res?.code, '错误描述:', res?.description);
      showToast('查询失败' + (res?.description ? `: ${res.description}` : ''));
    }
  } catch (error) {
    // 将捕获的错误封装为标准Error对象
    const followError = error instanceof Error 
      ? error 
      : new Error('查询粉丝/关注列表出错: ' + (error ? String(error) : '未知错误'));
    
    console.error('查询粉丝/关注列表出错:', followError);
    showToast('查询数据时发生错误，请稍后再试');
  }
});
</script>